<template>
  <el-dialog :title="examInfo.title ? examInfo.title : '考试试卷'" :visible.sync="visible" :append-to-body="appendToBody" fullscreen @close="onClose">
    <el-row :gutter="20">
      <el-col :span="19">
        <el-card style="padding: 15px;" shadow="hover">
          <template slot="header">
            <strong>{{ questionType }}题</strong>
          </template>
          <!-- 题目区 -->
          <el-row class="question-title m-t-20" :gutter="10">
            <el-col :span="24">
              <el-link type="primary" class="m-r-10 fr">{{ questionInfo.score + '分' }}</el-link>
            </el-col>
            <el-col :span="24">
              <span class="m-r-10">{{ '第' + questionInfo.questionNumber + '题' }}、 </span><span v-html="questionInfo.content"></span>
            </el-col>
          </el-row>
          <!-- 作题区 -->
          <el-row class="question-options m-t-20">
            <!-- 单选 -->
            <el-col v-if="questionInfo.type == '0'" :span="24">
              <div class="question-options-item">
                <text-select v-if="questionInfo.optionType == '0'" :value="questionInfo.answer" :disabled="hasSubmit" :options="questionInfo.options" :direction="'vertical'" @input="combineAnswer" />
                <image-select v-if="questionInfo.optionType == '1'" :value="questionInfo.answer" :disabled="hasSubmit" :options="questionInfo.options" :direction="'vertical'" @input="combineAnswer" />
                <audio-select v-if="questionInfo.optionType == '2'" :value="questionInfo.answer" :disabled="hasSubmit" :options="questionInfo.options" :direction="'vertical'" @input="combineAnswer" />
              </div>
            </el-col>
            <!-- 多选 -->
            <el-col v-if="questionInfo.type == '1'" :span="24">
              <div class="question-options-item">
                <text-select v-if="questionInfo.optionType == '0'" multiple :value="optionsAnswer" :disabled="hasSubmit" :options="questionInfo.options" :direction="'vertical'" @input="combineCheckboxAnswer" />
                <image-select v-if="questionInfo.optionType == '1'" multiple :value="optionsAnswer" :disabled="hasSubmit" :options="questionInfo.options" :direction="'vertical'" @input="combineCheckboxAnswer" />
                <audio-select v-if="questionInfo.optionType == '2'" multiple :value="optionsAnswer" :disabled="hasSubmit" :options="questionInfo.options" :direction="'vertical'" @input="combineCheckboxAnswer" />
              </div>
            </el-col>
            <!-- 判断 -->
            <el-col v-if="questionInfo.type == '2'" :span="24">
              <el-radio v-model="questionInfo.answer" label="Y" :disabled="hasSubmit">对</el-radio>
              <el-radio v-model="questionInfo.answer" label="N" :disabled="hasSubmit">错</el-radio>
            </el-col>
            <!-- 填空 -->
            <el-col v-if="questionInfo.type == '3'" :span="24">
              <div class="blank_option-item" v-for="(option, index) in questionInfo.options" :key="'option_blank_' + index">
                <strong>第{{ index + 1 }}空：</strong>
                <el-input v-model="option.value" class="underline" style="width: 150px;" :disabled="hasSubmit" @input="combineBlankAnswer" />
              </div>
            </el-col>
            <!-- 主观题 -->
            <el-col v-if="questionInfo.type == '4'" :span="24">
              <el-input
                type="textarea"
                :rows="5"
                placeholder="请输入答案"
                :disabled="hasSubmit"
                v-model="questionInfo.answer">
              </el-input>
            </el-col>
          </el-row>
          <!-- 保存区 -->
          <el-row class="m-t-20">
            <el-button v-if="questionInfo.questionNumber > 1" class="fl" type="primary" icon="el-icon-back" plain @click="lastQuestion">保存并上一题</el-button>
            <el-button v-if="questionInfo.questionNumber < totalQuestion" class="fr" type="primary" icon="el-icon-right" @click="nextQuestion">保存并下一题</el-button>
            <el-button v-if="questionInfo.questionNumber == totalQuestion && !hasSubmit" class="fr" type="primary" icon="el-icon-right" @click="confirmQuestion">提交</el-button>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="5">
        <el-card v-if="examInfo.score != undefined" shadow="always" class="m-b-20">
          <el-result sub-title="成绩">
            <template slot="icon">
              <span style="font-size: 36px; color: red;">{{ examInfo.score }}分</span>
            </template>
          </el-result>
        </el-card>
        <el-card v-if="!hasSubmit" shadow="always">
          <template slot="header">
            <strong style="font-size: 14px;">回答状态</strong><br>
            <small style="font-size: 10px; color: #8c939d">红色代表未回答,绿色代表已回答</small>
          </template>
          <el-tag v-for="(answer, index) in examInfo.questions" :key="'exam_answer_status_' + index" :type="answer.answered ? 'success' : 'danger'" style="margin: 10px 5px 5px 5px;">
            {{ '第' + (index + 1) + '题' }}
          </el-tag>
        </el-card>
        <el-card v-if="hasSubmit" shadow="always">
          <template slot="header">
            <strong style="font-size: 14px;">答案</strong><br>
            <small style="font-size: 10px; color: #8c939d">红色代表回答错误,绿色代表回答正确</small>
            <el-link v-if="examInfo.score && examInfo.score > 2" type="primary" class="fr" icon="el-icon-download" @click="handleCert()">电子证书</el-link>
          </template>
          <el-tag v-for="(answer, index) in examInfo.questions" :key="'exam_answer_status_' + index" :type="answer.isCorrect ? 'success' : 'danger'" style="margin: 10px 5px 5px 5px;">
            {{ '第' + (index + 1) + '题' }}
          </el-tag>
        </el-card>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
import TextSelect from '@/components/Form/TextSelect'
import ImageSelect from '@/components/Form/ImageSelect'
import AudioSelect from '@/components/Form/AudioSelect'
import { examCert, examPreview, examScore } from '@/api/training/exam'

export default {
  name: 'ExamPreview',
  components: {
    TextSelect,
    ImageSelect,
    AudioSelect
  },
  computed: {
    questionType() {
      switch (this.questionInfo.type) {
        case '0':
          return '单选'
        case '1':
          return '多选'
        case '2':
          return '判断'
        case '3':
          return '填空'
        case '4':
          return '简答'
        default:
          return ''
      }
    }
  },
  data() {
    return {
      visible: false,
      appendToBody: false,
      examInfo: {
        examId: undefined,
        courseId: undefined,
        title: undefined,
        introduce: undefined,
        questions: [],
        score: undefined
      },
      questionInfo: {
        questionNumber: 1,
        questionId: undefined,
        type: '0',
        optionType: '0',
        content: undefined,
        analysis: undefined,
        answer: undefined,
        difficulty: 1,
        score: 1,
        tagId: undefined,
        options: [],
        answered: false,
        isCorrect: undefined
      },
      optionsAnswer: [],
      totalQuestion: 0,
      hasSubmit: false
    }
  },
  methods: {
    init(examId) {
      this.clearData()
      this.visible = true
      this.$nextTick(() => {
        examPreview(examId).then(response => {
          this.$api.objectUpdate(this.examInfo, response.param)
          if (this.examInfo.questions.length > 0) {
            this.totalQuestion = this.examInfo.questions.length
            this.questionInfo.questionNumber = 1
            this.$api.objectUpdate(this.questionInfo, this.examInfo.questions[0])
          }
        })
      })
    },
    combineAnswer(val) {
      this.questionInfo.answer = val
    },
    combineCheckboxAnswer(val) {
      this.questionInfo.answer = val?.join('{:}')??''
    },
    combineBlankAnswer() {
      let answer = []
      this.questionInfo.options.forEach(option => {
        answer.push(option.value)
      })
      this.questionInfo.answer = answer?.join('{:}')??''
    },
    lastQuestion() {
      let index = this.questionInfo.questionNumber
      this.examInfo.questions[index - 1].answer = this.questionInfo.answer
      this.examInfo.questions[index - 1].answered = this.questionInfo.answer ? true : false
      this.clearQuestion()
      this.questionInfo = this.examInfo.questions[index - 2]
      this.questionInfo.questionNumber = index - 1
      this.setAnswer()
    },
    nextQuestion() {
      let index = this.questionInfo.questionNumber
      this.examInfo.questions[index - 1].answer = this.questionInfo.answer
      this.examInfo.questions[index - 1].answered = this.questionInfo.answer ? true : false
      this.clearQuestion()
      this.questionInfo = this.examInfo.questions[index]
      this.questionInfo.questionNumber = index + 1
      this.setAnswer()
    },
    setAnswer() {
      if (this.questionInfo.type === '1' || this.questionInfo.type === '3') {
        this.optionsAnswer = this.questionInfo.answer?.split('{:}')??[]
      }
    },
    confirmQuestion() {
      let index = this.questionInfo.questionNumber
      this.examInfo.questions[index - 1].answer = this.questionInfo.answer
      this.examInfo.questions[index - 1].answered = this.questionInfo.answer ? true : false
      this.setAnswer()

      this.$confirm('确定要提交试卷?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        this.hasSubmit = true
        examScore(this.examInfo).then(response => {
          this.clearData()
          this.$api.objectUpdate(this.examInfo, response.param)
          if (this.examInfo.questions.length > 0) {
            this.totalQuestion = this.examInfo.questions.length
            this.questionInfo.questionNumber = 1
            this.$api.objectUpdate(this.questionInfo, this.examInfo.questions[0])
            this.setAnswer()
          }
        })
      })
    },
    handleCert() {
      this.$modal.loading('正在生成证书...')
      examCert(this.examInfo.examId).then(response => {
        window.location.href = this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/public/file/download/` + response.param + '?delete=true'
        this.$modal.closeLoading()
      }).catch(e => { this.$modal.closeLoading() })
    },
    clearData() {
      this.totalQuestion = 0
      this.examInfo = {
        examId: undefined,
        courseId: undefined,
        title: undefined,
        introduce: undefined,
        questions: [],
        score: undefined
      }
      this.clearQuestion()
    },
    clearQuestion() {
      this.questionInfo = {
        questionNumber: 1,
        questionId: undefined,
        type: '0',
        optionType: '0',
        content: undefined,
        analysis: undefined,
        answer: undefined,
        difficulty: 1,
        score: 1,
        tagId: undefined,
        options: [],
        answered: false,
        isCorrect: undefined
      }
      this.optionsAnswer = []
    },
    onClose() {
      this.clearData()
      this.hasSubmit = false
      this.visible = false
    }
  }
}
</script>
<style lang="less" scoped>
.question-title {
  font-weight: bold;
}
</style>
